package com.egao.common.manage.student;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.egao.common.core.annotation.ApiPageParam;
import com.egao.common.core.annotation.OperLog;
import com.egao.common.core.exception.BusinessException;
import com.egao.common.core.web.BaseController;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.core.web.PageResult;
import com.egao.common.module.counsel.CounselConstants;
import com.egao.common.module.counsel.entity.Counsel;
import com.egao.common.module.counsel.entity.CounselStudent;
import com.egao.common.module.counsel.entity.CounselStudentFeedback;
import com.egao.common.module.counsel.entity.CounselTeacher;
import com.egao.common.module.counsel.enums.CounselTypeEnum;
import com.egao.common.module.counsel.param.CounselStudentParam;
import com.egao.common.module.counsel.service.CounselService;
import com.egao.common.module.counsel.service.CounselStudentFeedbackService;
import com.egao.common.module.counsel.service.CounselStudentService;
import com.egao.common.module.student.entity.Student;
import com.egao.common.module.student.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author lym
 * @date 2022/2/15 9:12
 */
@Api(tags = "学生预约咨询管理")
@RestController
@RequestMapping("${api}")
public class StudentCounselController extends BaseController {

    @Autowired
    private CounselService counselService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private CounselStudentService counselStudentService;
    @Autowired
    private CounselStudentFeedbackService counselStudentFeedbackService;

    @PreAuthorize("hasAuthority('student')")
    @ApiOperation(value = "（学生端）预约列表")
    @ApiPageParam
    @GetMapping("/student/counsel/page")
    public PageResult<CounselStudent> studentRecord(HttpServletRequest request) {
        PageParam<CounselStudent> pageParam = new PageParam<>(request);
        pageParam.put("student_id", getLoginUserId());
        return new PageResult<>(counselStudentService.listPage(pageParam), pageParam.getTotal());
    }

    @PreAuthorize("hasAuthority('student')")
    @ApiOperation(value = "学生预约咨询详情")
    @ApiPageParam
    @GetMapping("/student/counsel/{id}")
    public JsonResult detail(@PathVariable Integer id) {
        PageParam<CounselStudent> pageParam = new PageParam<>();
        pageParam.put("id", id);
        return JsonResult.ok().setData(pageParam.getOne(counselStudentService.listPage(pageParam)));
    }

    @PreAuthorize("hasAuthority('student')")
    @ApiOperation(value = "学生取消预约")
    @OperLog(value = "学生取消预约", desc = "学生取消预约", result = true)
    @PutMapping("/student/counsel/cancel/{id}")
    public JsonResult studentCancel(@PathVariable("id") Integer id) {
        LambdaQueryWrapper<CounselStudent> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CounselStudent::getId, id);
        CounselStudent counselStudent = counselStudentService.getOne(lqw);

        LambdaQueryWrapper<Counsel> clqw = new LambdaQueryWrapper<>();
        clqw.eq(Counsel::getId, counselStudent.getCounselId());
        Counsel counsel = counselService.getOne(clqw);

        String dateTimeStr = DateUtil.formatDateTime(counsel.getCounselDate());
        String startTimeStr = dateTimeStr.split(" ")[0] + " " + counsel.getCounselTime().split("-")[0];
        Date startTime = DateUtil.parse(startTimeStr);
        Date now = DateUtil.date();

        if (now.after(startTime)) {
            return JsonResult.error("预约时间已过不可取消！");
        }

        counselStudent.setState(CounselConstants.STUDENT_STATE_CANCEL);

        if (!counselStudentService.updateById(counselStudent)) {
            return JsonResult.error();
        }
        return JsonResult.ok();
    }


    @Transactional
    @PreAuthorize("hasAuthority('student')")
    @ApiOperation(value = "学生反馈")
    @OperLog(value = "预约咨询管理", desc = "学生反馈", result = true)
    @PostMapping("/student/counsel/feedback")
    public JsonResult feedback(@RequestBody CounselStudentFeedback counselStudentFeedback) {
        if (counselStudentFeedbackService.save(counselStudentFeedback)) {
            LambdaUpdateWrapper<CounselStudent> luw = new LambdaUpdateWrapper<>();
            luw.eq(CounselStudent::getId, counselStudentFeedback.getCounselStudentId())
                    .set(CounselStudent::getStudentFeedback, CounselConstants.FEEDBACK_STATE);
            if (counselStudentService.update(luw)) {
                return JsonResult.ok("操作成功！");
            }
        }
        return JsonResult.error("操作失败！");
    }

    @PreAuthorize("hasAuthority('student')")
    @OperLog(value = "学生预约", desc = "学生预约", result = true)
    @ApiOperation("学生预约")
    @Transactional
    @PostMapping("/student/counsel")
    public JsonResult save(@RequestBody CounselStudentParam studentParam) {
        Counsel counsel = counselService.getById(studentParam.getId());
        if (counsel.getSurplusCount() <= 0) {
            throw new BusinessException("当前咨询场次已经约满！");
        }
        Student student = studentService.getByUserId(getLoginUserId());
        // 查询学生是否已经预约当前的咨询
        LambdaQueryWrapper<CounselStudent> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CounselStudent::getCounselId, studentParam.getId())
                .eq(CounselStudent::getStudentId, student.getId());
        if (counselStudentService.getOne(lqw) != null) {
            throw new BusinessException("您已经预约过当前的咨询！");
        }
        CounselStudent counselStudent = new CounselStudent();
        BeanUtils.copyProperties(studentParam, counselStudent);
        counselStudent.setCounselId(studentParam.getId());
        counselStudent.setStudentId(student.getId());
        counselStudent.setCounselTeacherId(counsel.getCounselTeacherId());
        counselStudent.setState(CounselConstants.COUNSEL_STATE);
        counselStudent.setTitle(CounselTypeEnum.getByValue(studentParam.getCounselType()).getLabel());
        if (!counselStudentService.save(counselStudent)) {
            throw new BusinessException("预约失败, 请联系管理员");
        }
        LambdaUpdateWrapper<Counsel> luw = new LambdaUpdateWrapper<>();
        luw.eq(Counsel::getId, studentParam.getId());
        luw.set(Counsel::getSurplusCount, counsel.getSurplusCount() - 1);
        luw.set(Counsel::getVersion, counsel.getVersion() + 1);
        if (!counselService.update(luw)) {
            throw new BusinessException("预约失败, 请联系管理员");
        }
        return JsonResult.ok("预约成功");
    }

    @PreAuthorize("hasAuthority('student')")
    @ApiOperation(value = "咨询反馈详情")
    @GetMapping("/student/counsel/feedback/{id}")
    public JsonResult feedback(@PathVariable("id") Integer id) {
        List<CounselStudentFeedback> list = counselStudentFeedbackService.list(
                new LambdaQueryWrapper<CounselStudentFeedback>()
                        .eq(CounselStudentFeedback::getCounselStudentId, id)
                        .orderByDesc(CounselStudentFeedback::getId)
        );

        if (list.size() > 0) {
            return JsonResult.ok().setData(list.get(0));
        }
        return JsonResult.ok();
    }

}
